package com.jron.cqiu.kernel.implement;

import com.jron.cqiu.kernel.mail.IMailOrder;
import com.jron.cqiu.kernel.mail.IMail;
import com.jron.cqiu.kernel.persistence.IMailDao;
import com.jron.cqiu.kernel.execution.IExecution;
import com.jron.cqiu.util.ConfigurationUtil;
import com.jron.cqiu.util.StrUtil;
import com.jron.cqiu.Constants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.mail.EmailAttachment;

import javax.mail.Message;
import javax.mail.internet.MimeMessage;
import java.io.InputStream;
import java.io.IOException;

/**
 * Created by Intellij IDEA.
 *
 * @Author: Yejw
 * @Date: 2008-6-18
 * @Time: 9:34:28
 */
public class MailOrder implements IMailOrder {

    private static Log log = LogFactory.getLog(MailOrder.class);


    private String MAIL_O_PREFIX = "{";
    private String MAIL_O_SUFIX = "}";

    private String mailOrderMail = ConfigurationUtil.value("order.mail");
    private String mailOrderHost = ConfigurationUtil.value("order.mail.host");
    private String mailOrderUser = ConfigurationUtil.value("order.mail.user");
    private String mailOrderPassword = ConfigurationUtil.value("order.mail.password");
    private String mailOrderCommand = ConfigurationUtil.value("order.mail.command");

    public void execMailOrder() {
        try {
            fetchMailOrder(IMail.INSTANCE.receiveMail(mailOrderHost, mailOrderUser, mailOrderPassword));
            log.debug("Execution mail order over in this time.");
        } catch (Exception e) {
            log.warn(e.getMessage());
        }
    }

    /*
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
            "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>King 帮助信息</title>
    <style type="text/css">
        * {
            margin: 0;
            padding: 0
        }

        img {
            border: none
        }

        body {
            font-size: 14px;
            text-align: center;
            background: #EEF9FD;
        }

        #order {
            margin: 0 auto;
            width: 700px;
            height: auto;
        }

        #header {
            width: 100%;
            height: auto;
            margin-top: 5px;
        }

        dl {
            float: left;
            margin-left: 15px;
            width: 80px;
        }

        dt {
            width: 100%;
            border: 1px solid #B3D9EE;
            height: 24px;
            line-height: 24px;
            background: #E3F3FB;
            color: #10445C;
            font-weight: bold;
            letter-spacing: 2px;
        }

        dd {
            width: 100%;
            margin-top: 1px;
            border: 1px solid #B3D9EE;
            font-size: 1px;
            height: 4px;
            background: #B3D9EE
        }

        .s1 {
            font-size: 12px;
            font-weight: normal;
        }

        .s2 {
            font-size: 16px;
            font-weight: normal;
        }

        h3 {
            height: 33px;
            line-height: 30px;
            text-align: left;
            text-indent: 20px;
        }

        #order table {
            width: 100%;
            border: 1px #B3D9EE solid;
            border-bottom: 0
        }

        #order th, #order td {
            border-top: 1px #FFF solid;
            border-bottom: 1px #B3D9EE solid;
            height: 30px;
            line-height: 30px;
            color: #10445C;
        }

        #order th {
            width: 20%;
            text-align: right;
            background: #D6EDF8;
            font-weight: normal;
            border-left: 1px solid #FFF
        }

        #order td {
            text-indent: 5px;
            background: #E3F3FB;
            text-align: left;
        }
    </style>
    </head>
    <body>
    <div id="order">
        <div id="header">
            <dl>
                <dt><span class="s2">)</span><span class="s1">)</span>帮助<span class="s1">(</span><span class="s2">(</span>
                </dt>
                <dd></dd>
            </dl>
            <h3>
                Hakuna Matata! No worries for the rest of your days.
            </h3>
        </div>
        <table cellpadding="0" cellspacing="0">
            <tr>
                <th>结束进程：</th>
                <td>{ Kill pidName }</td>
                <td>arg1:进程名称</td>
            </tr>
            <tr>
                <th>结束进程：</th>
                <td>{ kill pidName ignoreCase }</td>
                <td> arg1:进程名称 arg2:忽略大小写(true or false)</td>
            </tr>

            <tr>
                <th>结束进程：</th>
                <td>{ kill_pid pid }</td>
                <td>arg1:进程ID</td>
            </tr>
            <tr>
                <th>邮件命令列表：</th>
                <td>{ hakunamatata }</td>
                <td></td>
            </tr>
            <tr>
                <th>邮件命令列表：</th>
                <td>{ hakunamatata to }</td>
                <td> arg1:发送到指定邮箱</td>
            </tr>
            <tr>
                <th>关机：</th>
                <td>{ shutdown }</td>
                <td></td>
            </tr>
            <tr>
                <th>关机：</th>
                <td>{ shutdown flag }</td>
                <td> arg1: 强制(NONE, FORCE, FORCEIFHUNG)</td>
            </tr>

            <tr>
                <th>重启：</th>
                <td>{ restart }</td>
                <td></td>
            </tr>
            <tr>
                <th>重启：</th>
                <td>{ restart flag }</td>
                <td> arg1: 强制(NONE, FORCE, FORCEIFHUNG)</td>
            </tr>
            <tr>
                <th>注销：</th>
                <td>{ logoff }</td>
                <td></td>
            </tr>
            <tr>
                <th>注销：</th>
                <td>{ logoff flag }</td>
                <td> arg1: 强制(NONE, FORCE, FORCEIFHUNG)</td>
            </tr>
            <tr>
                <th>定时关机：</th>
                <td>{ shutdown_at }</td>
                <td> arg1:默认为12:00</td>
            </tr>
            <tr>
                <th>倒计时关机：</th>
                <td>{ shutdown_time }</td>
                <td>arg1:默认为100秒</td>
            </tr>
            <tr>
                <th>复制文件：</th>
                <td>{ copy }</td>
                <td>arg1: 源文件(eg: C:\\test.txt) arg 2: 目标文件夹(eg: C:\\WINDOWS\\system32)</td>
            </tr>
        </table>

    </div>

    </body>
    </html>
     */
    public void sendHelp(String to) {
        String body = null;
        String relatedPath = ConfigurationUtil.value("order.mail.help.related.path");
        /*
        String fp = FilePath.getFullPathRelateClass(relatedPath, MailOrder.class);
        try {
            body = FileUtils.readFileToString(new File(fp), ConfigurationUtil.value("mail.default.charset"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        */
        InputStream is = getClass().getResourceAsStream(relatedPath);
        try {
            body = IOUtils.toString(is, ConfigurationUtil.value("mail.default.charset"));
        } catch (IOException e) {
            log.debug(e.getMessage());
            return;
        }

        EmailAttachment attachment = new EmailAttachment();
        attachment.setURL(getClass().getResource(relatedPath));
        attachment.setDisposition(EmailAttachment.ATTACHMENT);
        attachment.setDescription("King Help");
        attachment.setName("KingHelp.html");

        IMail.INSTANCE.sendAttachmentMail(to, "Sir", mailOrderMail, "King by jronrun",
                "King Help", body, attachment);

/*
        String kh = FilePath.getParentAbsolutePath("KingHelp.html");
        if (new File(kh).exists()) {
            EmailAttachment attachment = new EmailAttachment();
            //attachment.setURL(getClass().getResource(relatedPath));
            attachment.setPath(kh);
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            attachment.setDescription("King Help");
            attachment.setName("KingHelp.html");

            IMail.INSTANCE.sendAttachmentMail(to, "Sir", mailOrderMail, "King by jronrun",
                    "King Help", body, attachment);
        } else IMail.INSTANCE.sendSimpleMail(to, "Sir", mailOrderMail, "King by jronrun", "King Help", body);
*/

    }

    public void sendOrder(String order, String orderFrom) {
        order = (StringUtils.contains(order, MAIL_O_PREFIX) ? order : MAIL_O_PREFIX + order);
        order = (StringUtils.contains(order, MAIL_O_SUFIX) ? order : order + MAIL_O_SUFIX);
        IMail.INSTANCE.sendSimpleMail(mailOrderMail, orderFrom, mailOrderCommand, order);
    }

    private void fetchMailOrder(Message... mails) throws Exception {
        PraseMimeMessage pmm = null;
        IMailDao iMailDao = IMailDao.INSTANCE;
        log.debug("It has " + mails.length + " mails");

        for (Message mail : mails) {
            pmm = new PraseMimeMessage((MimeMessage) mail);
            String cid = pmm.getMessageId();
            pmm.setDateFormat(Constants.DEFAULT_DATE_FORMAT);
            String cTime = pmm.getSentDate();

            if (StringUtils.contains(pmm.getSubject(), mailOrderCommand) && iMailDao.isNewCommand(cid, cTime)) {
                pmm.getMailContent(mail);
                if (analyzeMailOrder(pmm.getBodyText(), pmm.getFrom())) iMailDao.signExecCommand(cid, cTime);
            }

        }

    }

    private boolean analyzeMailOrder(String mailBody, String mailFrom) {
        mailBody = StringUtils.substringBetween(mailBody, MAIL_O_PREFIX, MAIL_O_SUFIX);
        log.debug("The mail order is: " + mailBody);

        String tokens[] = StrUtil.argsToStringArray(mailBody);
        String orderMethod = tokens[0];
        String[] args = new String[tokens.length - 1];
        System.arraycopy(tokens, 1, args, 0, args.length);

        try {
            IExecution.INSTANCE.execMailOrder(orderMethod, mailFrom, args);
        } catch (Exception e) {
            log.warn("Execution mail order falied! " + e.getMessage());
            return false;
        }
        return true;
    }

}
